import React, { useState, useEffect, useCallback } from 'react';
import { Table, Input, Button, Space, Typography, message, Card, Layout, Empty } from 'antd';
import { SearchOutlined, ClockCircleOutlined, FolderOpenOutlined, RestOutlined, PlusOutlined } from '@ant-design/icons';
import type { MenuItem } from '../types/menu';
import http from '../api/http';
import {Add} from './add'
import {Edit}from './edit'
import type { IMenus } from '~/types/system';
const { Title } = Typography;
const { Content } = Layout;

// 统一样式常量，便于维护
const STYLE_CONSTANTS = {
  cardMarginBottom: 16, // 卡片底部间距
  contentPadding: '0 24px', // 内容区内边距
  contentMargin: '24px 0', // 内容区外边距
  tableBorderRadius: 8, // 表格卡片圆角
  buttonMarginLeft: 8, // 按钮左侧间距
  inputMaxWidth: 360, // 输入框最大宽度，限制输入框尺寸
};

interface PaginationState {
  current: number;
  pageSize: number;
}

const MenuManagement: React.FC = () => {
  const [menuList, setMenuList] = useState<MenuItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [totalCount, setTotalCount] = useState(0);
  const [pagination, setPagination] = useState<PaginationState>({
    current: 1,
    pageSize: 4,
  });

  // 请求参数生成
  const getRequestParams = () => ({
    name: searchKeyword.trim(),
    page: pagination.current,
    size: pagination.pageSize
  });

  // 获取菜单列表
  const fetchMenuList = useCallback(async () => {
    setLoading(true);
    try {
      const params = getRequestParams();
      http.getList<MenuItem>('/Menus/page', params).then(res => {
        if (res.code === '1') {
          setMenuList(res.data || []);
          setTotalCount(res.count || 0);
        }
      });
    } catch (error) {
      message.error('获取菜单列表失败，请重试');
      console.error('菜单查询错误:', error);
      setMenuList([]);
      setTotalCount(0);
    } finally {
      setLoading(false);
    }
  }, [pagination.current, pagination.pageSize, searchKeyword]);

  // 初始化加载
  useEffect(() => {
    fetchMenuList();
  }, [fetchMenuList, pagination]);

  // 搜索处理 - 仅通过按钮点击触发
  const handleSearch = () => {
    setPagination(prev => ({ ...prev, current: 1 }));
    fetchMenuList();
  };

  // 分页变更处理
  const handlePaginationChange = (current: number, pageSize: number) => {
    const maxPage = Math.ceil(totalCount / pageSize) || 1;
    const validCurrent = Math.max(1, Math.min(current, maxPage));
    setPagination({ current: validCurrent, pageSize });
  };

  // 重置 + 刷新功能
  const handleReset = () => {
    setSearchKeyword('');
    setPagination({ current: 1, pageSize: 4 });
    fetchMenuList();
    message.success('已重置搜索条件并刷新列表');
  };
    const [isModalOpen, setIsModalOpen] = useState(false);


  const showModal = () => {
    setIsModalOpen(true);
  };


  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const del=(id:number)=>{
 http.delete("Menus",{id:id}).then(res=>{
  if(res.code=='1'){
   message.success(res.msg)
   handleSearch()
  }
 })
  }
// 2. 添加修改弹框状态
const [editModalVisible, setEditModalVisible] = useState(false);
const [currentEditingMenu, setCurrentEditingMenu] = useState<MenuItem | null>(null);

// 3. 打开修改弹框（点击“编辑”按钮时触发）
const handleOpenEditModal = (menu: MenuItem) => {
  console.log(menu)
  setCurrentEditingMenu(menu);
  setEditModalVisible(true);
};

// 4. 关闭修改弹框
const handleCloseEditModal = () => {
  setEditModalVisible(false);
  setCurrentEditingMenu(null);
};

  // 表格列配置
  const columns = [
    {
      title: '菜单ID',
      dataIndex: 'menuId',
      key: 'menuId',
      width: 100,
      align: 'center',
      fixed: 'left',
    },
    {
      title: '菜单名称',
      dataIndex: 'menuName',
      key: 'menuName',
      width: 200,
      render: (name: string, record: MenuItem) => (
        <Space size="middle">
          <span className={record.icon} style={{ fontSize: '16px' }}>
            {!record.icon && <FolderOpenOutlined />}
          </span>
          <span style={{ fontWeight: 500 }}>{name}</span>
        </Space>
      ),
    },
    {
      title: '父菜单',
      dataIndex: 'parentId',
      key: 'parentId',
      width: 180,
      align: 'center',
      render: (parentId: number) => (
        <span style={{ color: parentId === 0 ? '#1890ff' : '#666' }}>
          {parentId === 0 ? '顶级菜单' : `子菜单（ID：${parentId}）`}
        </span>
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'lastTime',
      key: 'lastTime',
      width: 220,
      align: 'center',
      render: (time: string) => (
        <Space size="small">
          <ClockCircleOutlined style={{ color: '#1890ff' }} />
          <span>{time ? time.replace('T', ' ') : '暂无数据'}</span>
        </Space>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      align: 'center',
      fixed: 'right',
      render: (record:IMenus) => (
        <Space size="small">
          <Button size="small" type="text" style={{ color: '#1890ff' }}  onClick={() => handleOpenEditModal(record)} >编辑</Button>
          <Button size="small" type="text" style={{ color: '#ff4d4f' }} onClick={()=>del(record.menuId)}>删除</Button>
        </Space>
      ),
    },
  ];

  return (
    <Layout style={{ minHeight: '100vh', background: '#f5f5f5' }}>
      <Content 
        style={{ 
          padding: STYLE_CONSTANTS.contentPadding, 
          margin: STYLE_CONSTANTS.contentMargin,
          background: '#f5f5f5' 
        }}
      >
        {/* 标题区 */}
        <Card 
          
          style={{ 
            marginBottom: STYLE_CONSTANTS.cardMarginBottom,
            boxShadow: '0 2px 8px rgba(0, 0, 0, 0.05)',
            background: '#fff'
          }}
        >
          <Title level={4} style={{ margin: '12px 0' }}>
            <FolderOpenOutlined style={{ marginRight: 8, color: '#1890ff' }} />
            菜单管理
          </Title>
        </Card>

        {/* 搜索区域 */}
        <Card 
         
          style={{ 
            marginBottom: STYLE_CONSTANTS.cardMarginBottom,
            padding: '16px 24px',
            background: '#fff'
          }}
        >
          <Space.Compact 
            style={{ width: '100%' }}
            size="middle"
          >
            <Input
              placeholder="请输入菜单名称进行模糊查询"
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
              // 移除了onKeyPress事件处理，不再响应回车键
              style={{ 
                flex: 1, 
                borderRadius: 4, 
                maxWidth: STYLE_CONSTANTS.inputMaxWidth,
                padding: '6px 12px',
                fontSize: '14px'
              }}
              prefix={
                <SearchOutlined 
                  style={{ color: '#ccc', fontSize: '14px' }}
                />
              }
              allowClear
            />
            <Button 
              type="primary" 
              onClick={handleSearch}
              icon={<SearchOutlined />}
            >
              搜索
            </Button>
            <Button 
              onClick={handleReset}
              style={{ marginLeft: STYLE_CONSTANTS.buttonMarginLeft }}
            >
              重置刷新
            </Button>
             <Button 
              type="primary" 
              icon={<PlusOutlined />}
              style={{ marginLeft: STYLE_CONSTANTS.buttonMarginLeft }}
              loading={loading}
              onClick={()=>showModal()}
            >
              添加菜单
            </Button>
          </Space.Compact>
        </Card>

        {/* 表格区域 */}
        <Card 
         
          style={{ 
            borderRadius: STYLE_CONSTANTS.tableBorderRadius,
            background: '#fff'
          }}
          loading={loading}
        >
          {menuList.length === 0 && !loading ? (
            <div style={{ 
              padding: '60px 20px', 
              textAlign: 'center' 
            }}>
              <Empty 
                description="暂无菜单数据" 
                image={Empty.PRESENTED_IMAGE_SIMPLE}
              >
                <Button type="primary" onClick={handleReset}>
                  <RestOutlined style={{ marginRight: 4 }} />
                  刷新列表
                </Button>
              </Empty>
            </div>
          ) : (
            <Table
              dataSource={menuList}
              columns={columns}
              rowKey="menuId"
              pagination={{
                current: pagination.current,
                pageSize: pagination.pageSize,
                total: totalCount,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条菜单`,
                pageSizeOptions: ['10', '20', '50'],
                onChange: handlePaginationChange,
                disabled: totalCount === 0,
              }}
              scroll={{ 
                x: 800,
                y: 'calc(100vh - 320px)'
              }}
              stableRowKeys
              rowClassName="table-row-hover"
            />
          )}
        </Card>
        <Add visible={isModalOpen} onCancel={handleCancel} onSuccess={fetchMenuList}  ></Add>
      <Edit
      visible={editModalVisible}
      onCancel={handleCloseEditModal}
      onSuccess={fetchMenuList} // 修改成功后刷新列表
      editingMenu={currentEditingMenu} // 传递待修改数据
    />
      </Content>
    </Layout>
  );
};

export default MenuManagement;